/**
 * 本地硬盘文件读取流对象
 * Copyright(C) 2018 liumurong
 */

import { SliceReadStream } from "./slicereadstream";
import * as path from "path";
import * as fse from "fs-extra";
import { LocalReceiver } from "./localreceiver";

/**
 * 硬盘....
 */
export class LocalReadStream extends SliceReadStream {
    /**
     * LocalReadStream
     * @param hash 文件Hash
     * @param directory 目录
     */
    constructor(hash: string, directory: string, private receiver: LocalReceiver) {
        super(hash, directory);
    }
    /**
     * 读取文件
     */
    async _read() {
        let filePath = path.join(this.source, this.hash);
        if (!await fse.pathExists(filePath)) {
            this.emit("error", "文件不存在");
            this.push(null);
            return;
        }
        if (!this.metadata) {
            this.metadata = await this.receiver.getMetadata(this.hash);
            
        }
        // 文件合并完成
        if (this.sliceIndex === this.metadata.slicecount) {
            this.push(null);
            return;
        }
        let sliceFilePath = path.join(filePath, this.hash + "_" + this.sliceIndex + ".s");  // 文件以.s为后缀
        if (! await fse.pathExists(sliceFilePath)) {
            this.push(null);
            return;
        }
        this.sliceIndex++;
        let chunk = await fse.readFile(sliceFilePath);
        this.push(chunk);
    }
}

